package org.zfes.snowier.common.monitor.biz.service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zfes.snowier.common.monitor.biz.dao.ZActuatorMapper;
import org.zfes.snowier.common.monitor.biz.model.MysqlAcutor;
import org.zfes.snowier.common.monitor.biz.model.ZActuatorEntity;
import org.zfes.snowier.common.monitor.jvm.Server;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ZActuatorService {
    @Autowired
    private ZActuatorMapper actuatorMapper;

 
	public List<ZActuatorEntity> findAllByGroupKey(String groupKey) {
    	Map<String, Object> paramMap=new HashMap<>();
    	paramMap.put("groupKey", groupKey);
        return actuatorMapper.selectList(new QueryWrapper(paramMap));
    }
	@Transactional
	public void save(ZActuatorEntity actuatorEntity) {
		actuatorMapper.insert(actuatorEntity);
	}

	@Async
	@Transactional
	public void createInstance( String instanceKey,String instanceInfo) {
		//Server server =	JSONObject.parseObject(instanceInfo, Server.class);
		//String instanceKey=server.getRunningInstance();
		String groupKey=StringUtils.substringBefore(instanceKey, "_");
		
		ZActuatorEntity actuatorEntity=	actuatorMapper.selectOne(new QueryWrapper(new HashMap() {{put("instanceKey", instanceKey);}}));
		if(actuatorEntity==null) {
			actuatorEntity=new ZActuatorEntity();
			actuatorEntity.setDate(new Date());
			actuatorEntity.setServerInfo(instanceInfo);
			actuatorEntity.setGroupKey(groupKey);
			actuatorEntity.setInstanceKey(instanceKey);
			actuatorMapper.insert(actuatorEntity);
		}else {
			actuatorEntity.setDate(new Date());
			actuatorEntity.setServerInfo(instanceInfo);
//			actuatorMapper.updateById(actuatorEntity);
			actuatorMapper.update(actuatorEntity, new UpdateWrapper<ZActuatorEntity>().eq("instanceKey", instanceKey));
			
		}
		
	}


}
